<template>
  <div class="app-container">
    <!-- 添加Tabs标签页 -->
    <el-tabs v-model="activeTab" @tab-change="handleTabChange" class="mb-4">
      <el-tab-pane label="全部" name="all">
        <template #label>
          <span>全部</span>
        </template>
      </el-tab-pane>
      <el-tab-pane label="退货" name="退货">
        <template #label>
          <span style="color: #e6a23c;">退货</span>
        </template>
      </el-tab-pane>
      <el-tab-pane label="退款" name="退款">
        <template #label>
          <span style="color: #409eff;">退款</span>
        </template>
      </el-tab-pane>
      <el-tab-pane label="取消" name="取消">
        <template #label>
          <span style="color: #67c23a;">取消</span>
        </template>
      </el-tab-pane>
      <el-tab-pane label="投诉" name="投诉">
        <template #label>
          <span style="color: #f56c6c;">投诉</span>
        </template>
      </el-tab-pane>
    </el-tabs>

    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="订单号:" prop="orderId">
        <el-input
          v-model="queryParams.orderId"
          placeholder="请输入订单号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建人" prop="creator">
        <el-input
          v-model="queryParams.creator"
          placeholder="请输入创建人"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="添加数据时间" prop="applyTime">
        <el-date-picker clearable
          v-model="queryParams.applyTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择添加数据时间">
        </el-date-picker>
      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['orders:sale:add']"
        >新增</el-button>
      </el-col>
<!--      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['orders:sale:edit']"
        >修改</el-button>
      </el-col>-->
<!--      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['orders:sale:remove']"
        >删除</el-button>
      </el-col>-->
<!--     <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['orders:sale:export']"
        >导出</el-button>
      </el-col>-->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table 
      v-loading="loading" 
      :data="saleList" 
      @selection-change="handleSelectionChange"
      stripe
      border
      highlight-current-row
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="创建人" align="center" prop="creator" min-width="120" />
      <el-table-column label="订单号" align="center" prop="orderId" min-width="120" />
      <el-table-column label="原因" align="center" prop="reasonDesc" min-width="200" show-overflow-tooltip />
             <el-table-column label="售后类型" align="center" prop="afterSaleType" min-width="120">
         <template #default="scope">
           <span :style="getAfterSaleTypeStyle(scope.row.afterSaleType)">
             {{ scope.row.afterSaleType || '-' }}
           </span>
         </template>
       </el-table-column>
      <el-table-column label="时间" align="center" prop="applyTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.applyTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template #default="scope">
          <el-button 
            link 
            type="primary" 
            icon="Edit" 
            @click="handleUpdate(scope.row)" 
            v-hasPermi="['orders:sale:edit']"
          >修改</el-button>
          <el-button 
            link 
            type="danger" 
            icon="Delete" 
            @click="handleDelete(scope.row)" 
            v-hasPermi="['orders:sale:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

         <!-- 添加或修改售后对话框 -->
     <el-dialog :title="title" v-model="open" width="600px" append-to-body>
       <el-form ref="saleRef" :model="form" :rules="rules" label-width="120px">
         <el-row :gutter="20">
           <el-col :span="12">
             <el-form-item label="订单号" prop="orderId">
               <el-input v-model="form.orderId" placeholder="请输入订单号" />
             </el-form-item>
           </el-col>
           <el-col :span="12">
             <el-form-item label="售后类型" prop="afterSaleType">
               <el-select v-model="form.afterSaleType" placeholder="请选择售后类型" style="width: 100%">
                 <el-option label="退货" value="退货" />
                 <el-option label="退款" value="退款" />
                 <el-option label="取消" value="取消" />
                 <el-option label="投诉" value="投诉" />
               </el-select>
             </el-form-item>
           </el-col>
         </el-row>
         <el-row :gutter="20">
           <el-col :span="12">
             <el-form-item label="创建人ID" prop="creatorId">
               <el-input 
                 v-model="form.creatorId" 
                 placeholder="请输入创建人ID" 
                 readonly 
                 style="background-color: #e6f7ff; color: #409eff; border-color: #b3d8ff;"
               />
             </el-form-item>
           </el-col>
           <el-col :span="12">
             <el-form-item label="创建人" prop="creator">
               <el-input 
                 v-model="form.creator" 
                 placeholder="请输入创建人" 
                 readonly 
                 style="background-color: #e6f7ff; color: #409eff; border-color: #b3d8ff;"
               />
             </el-form-item>
           </el-col>
         </el-row>
         <el-form-item label="售后原因描述" prop="reasonDesc">
           <el-input 
             v-model="form.reasonDesc" 
             type="textarea" 
             :rows="4"
             placeholder="请输入售后原因描述" 
           />
         </el-form-item>
                   <el-form-item label="添加数据时间" prop="applyTime">
            <el-date-picker 
              clearable
              v-model="form.applyTime"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择添加数据时间"
              style="width: 100%"
            />
          </el-form-item>
       </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Sale">
import { listSale, getSale, delSale, addSale, updateSale } from "@/api/orders/sale"
import useUserStore from '@/store/modules/user'

const { proxy } = getCurrentInstance()
const userStore = useUserStore()

const saleList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const activeTab = ref("all") // 当前激活的标签页

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderId: null,
    creatorId: null,
    creator: null,
    reasonDesc: null,
    afterSaleType: null,
    applyTime: null
  },
     rules: {
     orderId: [
       { required: true, message: "关联订单ID不能为空", trigger: "blur" }
     ],
     creator: [
       { required: true, message: "创建人不能为空", trigger: "blur" }
     ],
     afterSaleType: [
       { required: true, message: "售后类型不能为空", trigger: "change" }
     ],
     reasonDesc: [
       { required: true, message: "售后原因描述不能为空", trigger: "blur" }
     ],
     applyTime: [
       { required: true, message: "添加数据时间不能为空", trigger: "blur" }
     ]
   }
})

const { queryParams, form, rules } = toRefs(data)

// 售后类型样式映射
function getAfterSaleTypeStyle(type) {
  const styleMap = {
    '退款': 'color: #409eff; font-weight: bold; border: 1px solid #409eff; padding: 2px 8px; border-radius: 4px; background-color: #ecf5ff;', // 蓝色边框
    '投诉': 'color: #f56c6c; font-weight: bold; border: 1px solid #f56c6c; padding: 2px 8px; border-radius: 4px; background-color: #fef0f0;', // 红色边框
    '取消': 'color: #67c23a; font-weight: bold; border: 1px solid #67c23a; padding: 2px 8px; border-radius: 4px; background-color: #f0f9ff;', // 绿色边框
    '退货': 'color: #e6a23c; font-weight: bold; border: 1px solid #e6a23c; padding: 2px 8px; border-radius: 4px; background-color: #fdf6ec;'  // 黄色边框
  }
  return styleMap[type] || 'color: #606266; border: 1px solid #dcdfe6; padding: 2px 8px; border-radius: 4px; background-color: #f5f7fa;' // 默认灰色边框
}

/** 查询售后列表 */
function getList() {
  loading.value = true
  // 根据当前标签页设置查询条件
  const params = { ...queryParams.value }
  
  // 根据当前激活的标签页设置筛选条件
  if (activeTab.value && activeTab.value !== "all") {
    params.afterSaleType = activeTab.value
  } else {
    // 确保在"全部"标签页时清除售后类型筛选
    params.afterSaleType = null
  }
  
  console.log('查询参数:', params)
  console.log('当前标签页:', activeTab.value)
  
  listSale(params).then(response => {
    saleList.value = response.rows
    console.log('查询结果:', saleList.value)
    total.value = response.total
    loading.value = false
  }).catch(error => {
    console.error('查询数据失败:', error)
    loading.value = false
  })
}

/** 标签页切换处理 */
function handleTabChange(tabName) {
  // 重置分页
  queryParams.value.pageNum = 1
  // 清除其他查询条件，只保留标签页筛选
  queryParams.value.orderId = null
  queryParams.value.creator = null
  // 立即查询数据，确保标签页切换响应及时
  getList()
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    afterSaleId: null,
    orderId: null,
    creatorId: null,
    creator: null,
    reasonDesc: null,
    afterSaleType: null,
    applyTime: null
  }
  proxy.resetForm("saleRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  // 保持当前标签页状态，但重置其他查询条件
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  // 重置后回到"全部"标签页
  activeTab.value = "all"
  queryParams.value.pageNum = 1
  getList()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.afterSaleId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  // 自动填充当前登录用户信息
  form.value.creatorId = userStore.id
  form.value.creator = userStore.name
  // 设置当前时间精确到秒
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  const seconds = String(now.getSeconds()).padStart(2, '0')
  form.value.applyTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  open.value = true
  title.value = "添加售后"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _afterSaleId = row.afterSaleId || ids.value
  getSale(_afterSaleId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改售后"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["saleRef"].validate(valid => {
    if (valid) {
      // 处理提交数据
      const submitData = { ...form.value }
      
      // 确保时间格式正确
      if (submitData.applyTime) {
        // 如果是Date对象，转换为字符串
        if (submitData.applyTime instanceof Date) {
          const year = submitData.applyTime.getFullYear()
          const month = String(submitData.applyTime.getMonth() + 1).padStart(2, '0')
          const day = String(submitData.applyTime.getDate()).padStart(2, '0')
          const hours = String(submitData.applyTime.getHours()).padStart(2, '0')
          const minutes = String(submitData.applyTime.getMinutes()).padStart(2, '0')
          const seconds = String(submitData.applyTime.getSeconds()).padStart(2, '0')
          submitData.applyTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
        }
        // 确保时间格式为 YYYY-MM-DD HH:mm:ss
        if (typeof submitData.applyTime === 'string' && submitData.applyTime.includes('T')) {
          submitData.applyTime = submitData.applyTime.replace('T', ' ').substring(0, 19)
        }
      }
      
      if (submitData.afterSaleId != null) {
        updateSale(submitData).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addSale(submitData).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _afterSaleIds = row.afterSaleId || ids.value
  proxy.$modal.confirm('是否确认删除售后编号为"' + _afterSaleIds + '"的数据项？').then(function() {
    return delSale(_afterSaleIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('orders/sale/export', {
    ...queryParams.value
  }, `批量新增模版.xlsx`)
}

getList()
</script>

<style scoped>
.mb-4 {
  margin-bottom: 20px;
}

/* 标签页样式优化 */
:deep(.el-tabs__header) {
  margin-bottom: 20px;
  border-bottom: 1px solid #e4e7ed;
}

:deep(.el-tabs__item) {
  font-weight: 500;
  transition: all 0.3s;
  padding: 0 20px;
  height: 40px;
  line-height: 40px;
}

:deep(.el-tabs__item:hover) {
  color: #409eff;
}

:deep(.el-tabs__item.is-active) {
  font-weight: 600;
  color: #409eff;
}

:deep(.el-tabs__active-bar) {
  background-color: #409eff;
  height: 3px;
}

/* 标签页内容区域样式 */
:deep(.el-tabs__content) {
  padding: 0;
}

/* 搜索表单样式优化 */
:deep(.el-form--inline .el-form-item) {
  margin-right: 20px;
  margin-bottom: 18px;
}
</style>
